package leftMain;
//package org.dlsu.mt.parser;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.dlsu.mt.parser.TRANSFER.TransferDictionary;
import org.dlsu.mt.parser.dictionary.Dictionary;

public class AddEntryGUI extends JFrame implements MouseListener
{
		
	private Dictionary d;
	private org.dlsu.mt.parser.dictionary.DictionaryWord dw;
	private org.dlsu.mt.parser.dictionary.WordClass wc; 
	
	private JLabel labelWord;	
	private JTextField fieldWord;
	
	private JLabel labelPOS;
	private JLabel labelSemantics;
	private JLabel labelFschemata;
	private JLabel labelLFG;
	private JLabel labelLanguage;
		
	private JLabel labelTranslationWord;
	private JLabel labelTranslationPOS;
	private JLabel labelTranslationSemantics;
	private JLabel labelTranslationFschemata;
	private JLabel labelTranslationLFG;
	
	private JLabel labelRequiredFields;
	
	private JTextField fieldPOS;
	private JTextField fieldSemantics;
	private JTextField fieldFschemata;
	private JTextField fieldLFG;
	private JTextField translationWord;
	private JTextField translationPOS;
	private JTextField translationSemantics;
	private JTextField translationFschemata;
	private JTextField translationLFG;
	
	private JButton buttonSaveWord;
	private JButton buttonCancel;
	
	private JComboBox comboLanguage;
	private JCheckBox checkTranslation;
	
	private boolean modified = false;	
	private LEFTTranslator left;
	
	public AddEntryGUI(int x, int y, LEFTTranslator left)
	{
		this.left = left;
		
		setTitle("Add Entry");
		//setResizable(false);
		setAlwaysOnTop(true);
		setBounds((x+155), (y+100), 420, 350+60);
		getContentPane().setLayout(null);
		addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				if(modified)
					refresh();
				dispose();
				//System.exit(0);
			}
		});
		
		labelWord = new JLabel("Word:*");
		labelPOS = new JLabel("Part of Speech:*");
		labelSemantics = new JLabel("Semantics:");
		labelFschemata = new JLabel("Fschemata:");
		labelLFG = new JLabel("Lexical:");
		labelLanguage = new JLabel("Language:*");
		
		labelTranslationWord = new JLabel("Word:*");
		labelTranslationPOS = new JLabel("Part of Speech:*");
		labelTranslationSemantics = new JLabel("Semantics:");
		labelTranslationFschemata = new JLabel("FSchemata:");
		labelTranslationLFG = new JLabel("LFG");
		labelRequiredFields = new JLabel("Fields with (*) are required fields.");	
		
		fieldWord =  new JTextField();		
		fieldPOS =  new JTextField();
		fieldSemantics =  new JTextField();
		fieldFschemata =  new JTextField();
		fieldLFG = new JTextField();
		translationWord =  new JTextField();
		translationPOS = new JTextField();
		
		translationSemantics =  new JTextField();
		translationFschemata=  new JTextField();
		translationLFG = new JTextField();
		
		comboLanguage = new JComboBox();
		
		checkTranslation = new JCheckBox();
		//checkViceVersa = new JCheckBox();
		
		labelWord.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //labelWord.setText("Word: *");
		labelWord.setBounds(15, 7, 160, 25);
		getContentPane().add(labelWord);
		
		fieldWord.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
		fieldWord.setText("");
		fieldWord.setEditable(true);
		fieldWord.setBackground(Color.white);
		fieldWord.setBounds(165, 7, 230, 25);
		getContentPane().add(fieldWord);
		
		labelPOS.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //labelPOS.setText("Part of Speech: *");
		labelPOS.setBounds(15, 37, 160, 25);
		getContentPane().add(labelPOS);
		
		fieldPOS.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
		fieldPOS.setText("");
		fieldPOS.setEditable(true);
		fieldPOS.setBackground(Color.white);
		fieldPOS.setBounds(165, 37, 230, 25);
		getContentPane().add(fieldPOS);
		
		labelSemantics.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //labelSemantics.setText("Semantics:");
		labelSemantics.setBounds(15, 67, 160, 25);
		getContentPane().add(labelSemantics);
		
		fieldSemantics.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
		fieldSemantics.setText("");
		fieldSemantics.setEditable(true);
		fieldSemantics.setBackground(Color.white);
		fieldSemantics.setBounds(165, 67, 230, 25);
		getContentPane().add(fieldSemantics);		
		
		labelFschemata.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //labelFschemata.setText("Collocation:");
		labelFschemata.setBounds(15, 97, 160, 25);
		getContentPane().add(labelFschemata);
		
		fieldFschemata.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
		fieldFschemata.setText("");
		fieldFschemata.setEditable(true);
		fieldFschemata.setBackground(Color.white);
		fieldFschemata.setBounds(165, 97, 230, 25);
		getContentPane().add(fieldFschemata);	
		
		labelLFG.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //labelFschemata.setText("Collocation:");
		labelLFG.setBounds(15, 127, 160, 25);
		getContentPane().add(labelLFG);
		
		fieldLFG.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
		fieldLFG.setText("");
		fieldLFG.setEditable(true);
		fieldLFG.setBackground(Color.white);
		fieldLFG.setBounds(165, 127, 230, 25);
		getContentPane().add(fieldLFG);
		
		labelLanguage.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //labelLanguage.setText("Language: *");
		labelLanguage.setBounds(15, 127+30, 160, 25);
		getContentPane().add(labelLanguage);
		
		comboLanguage.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 16));
		comboLanguage.setBounds(165, 127+30, 230, 25);
		comboLanguage.addItem("Please choose language. . .");
		comboLanguage.addItem("English");
		comboLanguage.addItem("Filipino");
		comboLanguage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                //comboPOSActionPerformed(evt);
            }
        });
		getContentPane().add(comboLanguage);
		
		//labelTranslationWord = new JLabel();
		buttonSaveWord = new JButton();
		buttonCancel = new JButton();
		translationWord = new JTextField();
		
		checkTranslation.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        checkTranslation.setText("Include Translation");
		checkTranslation.setToolTipText("Include Translation");
		checkTranslation.setBounds(15, 175+30, 200, 25);
		checkTranslation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                boolean b;
                
                b = !translationPOS.isEnabled();                	
                translationWord.enable(b);
                translationPOS.enable(b);
                translationSemantics.enable(b);
                translationFschemata.enable(b);
                translationLFG.enable(b);
                                               
                repaint();
            	}
        });
        
		getContentPane().add(checkTranslation);
		
		//checkViceVersa.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        //checkViceVersa.setText("Vice versa");
		//checkViceVersa.setToolTipText("Vice versa");
		//checkViceVersa.setBounds(230, 175, 200, 25);		
		        
		//getContentPane().add(checkViceVersa);
		labelRequiredFields.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 10));
        labelRequiredFields.setBounds(230, 175+30, 200, 25);
		getContentPane().add(labelRequiredFields);
		
		labelTranslationWord.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 12));
        labelTranslationWord.setBounds(15, 210+30, 80, 25);
		getContentPane().add(labelTranslationWord);	
		
		translationWord.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 14));
        translationWord.setBounds(120, 210+30, 160, 20);
		translationWord.enable(false);		
		getContentPane().add(translationWord);
		
		labelTranslationPOS.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 10));
        labelTranslationPOS.setBounds(15, 235+30, 80, 25);
		getContentPane().add(labelTranslationPOS);
		
		translationPOS.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 14));
        translationPOS.setBounds(120, 235+30, 160, 20);
		translationPOS.enable(false);
		getContentPane().add(translationPOS);
		
		labelTranslationSemantics.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 12));
        labelTranslationSemantics.setBounds(15, 260+30, 80, 25);
		getContentPane().add(labelTranslationSemantics);
		
		translationSemantics.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 14));
        translationSemantics.setBounds(120, 260+30, 160, 20);
		translationSemantics.enable(false);
		getContentPane().add(translationSemantics);
		
		labelTranslationFschemata.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 12));
        labelTranslationFschemata.setBounds(15, 285+30, 80, 25);
		getContentPane().add(labelTranslationFschemata);
		
		translationFschemata.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 14));
        translationFschemata.setBounds(120, 285+30, 160, 20);
		translationFschemata.enable(false);
		getContentPane().add(translationFschemata);
		
		
		labelTranslationLFG.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 12));
        labelTranslationLFG.setBounds(15, 310+30, 80, 25);
		getContentPane().add(labelTranslationLFG);
		
		translationLFG.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 14));
        translationLFG.setBounds(120, 310+30, 160, 20);
		translationLFG.enable(false);
		getContentPane().add(translationLFG);
		
		buttonSaveWord.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        buttonSaveWord.setText("Save");
		buttonSaveWord.setToolTipText("Save");
		buttonSaveWord.setBounds(295, 255+60, 100, 25);
		buttonSaveWord.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveWordActionPerformed(evt);
            }
        });
		getContentPane().add(buttonSaveWord);		
		
		buttonCancel.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 16));
        buttonCancel.setText("Cancel");
		buttonCancel.setToolTipText("Cancel");
		buttonCancel.setBounds(295, 285+60, 100, 25);
		buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	if(modified)
            		refresh();
                dispose();
            }
        });
        
		getContentPane().add(buttonCancel);	
		
		setVisible(true);
		this.repaint();
	}
	
	public void mouseClicked(MouseEvent e)
	{
		
	}
	public void mouseEntered(MouseEvent e)
	{
		
	}
	public void mouseExited(MouseEvent e)
	{
		
	}
	public void mousePressed(MouseEvent e)
	{
		
	}
	public void mouseReleased(MouseEvent e)
	{
		
	}
		
	private boolean buttonSaveWordActionPerformed(java.awt.event.ActionEvent evt)
	{
		String lang = "", transLang = "";
		
				
		if(comboLanguage.getSelectedIndex() == 0 || fieldWord.getText().equals("") || fieldPOS.getText().equals("")){
			
			javax.swing.JOptionPane.showMessageDialog(this, "Required field(s) missing.", "Add Entry", javax.swing.JOptionPane.OK_OPTION);
		
		}
		else if(checkTranslation.isSelected() && (translationWord.getText().equals("") || translationPOS.getText().equals(""))){
			
			javax.swing.JOptionPane.showMessageDialog(this, "Required field(s) missing.", "Add Entry", javax.swing.JOptionPane.OK_OPTION);	
			
		}
		else{
			//System.out.println("abot hangang dito");
			if(comboLanguage.getSelectedIndex() == 1){			
				lang = "1";
				transLang = "2";
			}
			else{			
				lang = "2";
				transLang = "1";
			}
			
			if(checkForDuplicate(lang, fieldWord.getText(), fieldPOS.getText())){
				javax.swing.JOptionPane.showMessageDialog(this, "Word already exists.", "Add Entry", javax.swing.JOptionPane.OK_OPTION);
				return false;
			}			
			else{
				
				if(insertIntoDatabase(lang, fieldWord.getText(), fieldPOS.getText(), fieldSemantics.getText(), fieldFschemata.getText(), fieldLFG.getText())){
					boolean b = false;		
					boolean a = false;
					
					if(checkTranslation.isSelected()){
						
						a = insertTranslation(fieldWord.getText(), fieldPOS.getText(), lang, translationWord.getText(), translationPOS.getText(), transLang);
						b = insertTranslation(translationWord.getText(), translationPOS.getText(), transLang, fieldWord.getText(), fieldPOS.getText(), lang);
							
						if(a && b){
							javax.swing.JOptionPane.showMessageDialog(this, "Word with translation successfully added.", "Add Entry", 1);
							translationWord.setText("");
							translationPOS.setText("");
							translationSemantics.setText("");
							translationFschemata.setText("");
							translationLFG.setText("");
						}
						else
							javax.swing.JOptionPane.showMessageDialog(this, "Word successfully added.", "Add Entry", 1);						
					}
					else{
						
						javax.swing.JOptionPane.showMessageDialog(this, "Word successfully added.", "Add Entry", 1);
					}
					
					modified = true;					
					fieldWord.setText("");
					fieldPOS.setText("");
					fieldSemantics.setText("");
					fieldFschemata.setText("");
					fieldLFG.setText("");				
					comboLanguage.setSelectedIndex(0);
				}
				else{
					javax.swing.JOptionPane.showMessageDialog(this, "Word unsuccessfully added.", "Add Entry", javax.swing.JOptionPane.OK_OPTION);
					return false;
				}
			}				
			
			this.repaint();			
		}
		return true;
    }
    
    public boolean insertIntoDatabase(String lang, String word, String POS, String semantics, String fschemata, String lfg)
    {
    	boolean result = false;
    	String query = "";
    	String query2 = "";
   		
   		try{
   			
   			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        	
	        Connection con = DriverManager.getConnection("jdbc:odbc:leftDB", "",""); 
			
   			Statement stmt = con.createStatement();
   			
   			if(lang.equals("1")){   			
				query = "INSERT INTO language1Dict(word, POS, semantics, fschemata, lfg) Values ('"+word+"', '"+POS+"', '"+semantics+"', '"+fschemata+"', '"+lfg+"')";
				query2 = "SELECT id FROM language1Dict WHERE word = '"+word+"' AND POS = '"+POS+"'";
			}
   			else{
   			
   				query = "INSERT INTO language2Dict(word, POS, semantics, fschemata, lfg) Values ('"+word+"', '"+POS+"', '"+semantics+"', '"+fschemata+"', '"+lfg+"')";
   				query2 = "SELECT id FROM language2Dict WHERE word = '"+word+"' AND POS = '"+POS+"'";
   			}
   			ResultSet rs;
   			
   			try{		
				stmt.executeUpdate(query);			
				rs = stmt.executeQuery(query2);
			}catch(Exception e){
				return false;
			}
			
			rs.next();
			int id = rs.getInt("id");
			rs.close();
			
			try{
				query = "INSERT INTO transferDict(transferWordID, word, lang, POS) Values ('"+id+"', '"+word+"', '"+lang+"', '"+POS+"')";
System.out.println("INSERTED: -----------------------------");
				//stmt.executeUpdate(query);
			}catch(Exception e){
				return false;
			}
					
			stmt.close();
			con.close();			
			return true;
			
   		}catch(Exception e)		
		{
			System.out.println("Error "+e.toString());
			return false;
		}  	
    }
    
    private boolean checkForDuplicate(String lang, String word, String POS){
    	    	
    	String msg = "";
    	String query = "";
    	int counter = 0	;
   		
   		try{
   			
   			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        	
	        Connection con = DriverManager.getConnection("jdbc:odbc:leftDB", "",""); 
			
   			Statement stmt = con.createStatement();
   			
   			if(lang.equals("1"))
   				query = "SELECT * FROM language1Dict WHERE word = '"+word+"' AND POS = '"+POS+"'";
   			else
   				query = "SELECT * FROM language2Dict WHERE word = '"+word+"' AND POS = '"+POS+"'";
   			
   			
			ResultSet rs = stmt.executeQuery(query);
									
			try
			{
				while(rs.next())
					counter++;
			} catch ( SQLException e ) {}
			
			stmt.close();
			con.close();
			
			if(counter == 0)
				return false;
			else
				return true;
			
						
   		}catch(Exception e)
		{
			System.out.println("Error "+e.toString());
			msg = e.toString();
		}
		
    	return false;    	
    }
    
    public boolean insertTranslation(String origWord, String origPOS, String origLang, String transWord, String transPOS, String transLang){
		
		//if translation is english to filipino: lang = f
		//if translation is filipino to english: lang = e;
		String msg = "";
		String query = null;
		boolean result = true;
   	  		
   		try{
   			
   			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        	
	        Connection con = DriverManager.getConnection("jdbc:odbc:leftDB", "",""); 
			
   			Statement stmt = con.createStatement();
   			   				
			ResultSet rs;
			
			if(transLang.equals("1"))
				rs =  stmt.executeQuery("SELECT id FROM language1Dict Where word = '"+transWord+"' AND POS = '"+transPOS+"' ");
			else
				rs =  stmt.executeQuery("SELECT id FROM language2Dict Where word = '"+transWord+"' AND POS = '"+transPOS+"' ");
			
			
			try{
				
			rs.next();
			msg = (String)rs.getString( "id" );
			rs.close();
			
			}catch(Exception e){	
				
				if(javax.swing.JOptionPane.showConfirmDialog(this, " \" " + transWord + "\" is not found in the dictionary. Do you want to add it?", "Add Entry", 2, 3) == 0){
				
					//AddEntryGUI a = new AddEntryGUI(this.getX(), this.getY(), transWord, transPOS, transLang);
					
					//String semantics = javax.swing.JOptionPane.showInputDialog(this, "Enter Semantics", transWord, 3);
					//String collocation = javax.swing.JOptionPane.showInputDialog(this, "Enter Collocation", transWord, 3);
					
					insertIntoDatabase(transLang, transWord, transPOS, translationSemantics.getText(), translationFschemata.getText(), translationLFG.getText());
					result = insertTranslation(origWord, origPOS, origLang, transWord, transPOS, transLang);
					
				}
				else{
					return false;
				}				
			}			
			
			int transID = Integer.parseInt(msg);
			
			if(origLang.equals("1"))			
				rs =  stmt.executeQuery("SELECT id FROM language1Dict Where word = '"+origWord+"' AND POS = '"+origPOS+"' ");
			else
				rs =  stmt.executeQuery("SELECT id FROM language2Dict Where word = '"+origWord+"' AND POS = '"+origPOS+"' ");
			
			rs.next();
			msg = (String)rs.getString( "id" );
			rs.close();
			
			int origID = Integer.parseInt(msg);
			//System.out.println(origID + " ito");			
			
			//stmt.executeUpdate("UPDATE transferDict SET translation = '"+transID+"' Where transferWordID = "+origID+" And lang = '"+origLang+"' ");
			stmt.executeUpdate("INSERT INTO transferDict(transferWordID, word, pos, lang, translation) VALUES("+origID+", '"+origWord+"', '"+origPOS+"', '"+origLang+"', "+transID+")");
					
			stmt.close();
			con.close();
			System.out.println(origWord + " successful.");
			return true;
			
   		}catch(Exception e){
			System.out.println(origWord + " unsuccessful.");
			return result;
		}
	}
	
	public void refresh(){
		
		left.setLanguage1Dictionary(new Dictionary("Language1"));
		left.setLanguage2Dictionary(new Dictionary("Language2"));
		left.transfer = new TransferModule(left.language1Dictionary, left.language2Dictionary, left.glob);
		left.transferDictionary = new TransferDictionary();
	}
	
	
}